package com.tyjw.common;

import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class ToolUtil {

	
	public static String accessToken;
	public static int companyId;
	
	
	
	/**获取AccessToken**/
	public static void getAccessToken(String domain,String accessKeyID,String accessKeySecret) {
		long timeStamp=System.currentTimeMillis(); 
		String encryptStr=MD5(accessKeyID+accessKeySecret+timeStamp);
		Map<String,Object> data=new HashMap<>();
		data.put("accessKeyId", accessKeyID);
		data.put("encryptStr", encryptStr);
		data.put("timeStamp", timeStamp);
		String json=HttpUtils.httpPost(domain+"/eapi/auth/getToken", JSON.toJSONString(data), null);
		JSONObject jsonObj=JSON.parseObject(json);
		if(jsonObj.getIntValue("state")==0) {
			JSONObject content=jsonObj.getJSONObject("content");
			accessToken=content.getString("accessToken");
			companyId=content.getIntValue("companyId");
		}
	}
	
	
	
	private static String MD5(String str){
		try {
			MessageDigest crypt = MessageDigest.getInstance("MD5");
	        crypt.reset();
	        crypt.update(str.getBytes("UTF-8"));
	        return byteToHex(crypt.digest());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
    private static String byteToHex(byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash){
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}
